<template>
    <div class="content-box">
        <e-heading class="title" grade="1">赛程</e-heading>
        <!--赛程日期-->
        <date-slider v-model="activeDate" :list="dateList" @change="handleCheck"/>
        <div v-if="gameList.length">
          <!--赛程场地-->
          <place-group :list="matchList" v-model="selectedIndex" @change="handleSelect"/>
          <ul class="match-list small">
            <li v-for="(item,$index) in gameList" class="match-item  clearfix" 
                v-bind:class="{odd:$index%2==0}"
                :key="item.id">
                <el-row>
                  <el-col :span="4">
                    <div class="match-date">
                        <p>{{new Date(item.startTime).format("yyyy-MM-dd hh:mm:ss")}}</p>
                        <p>第{{item.grade}}轮</p>
                    </div>
                  </el-col>
                  <el-col :span="4">
                    <div class="team">
                      <div class="host tm-name">
                          <p v-if="doubleType.includes(race_detail.joinRequire)">{{item.hostUserName}} & {{item.hostUserName2}}</p>
                          <p v-else>{{item.hostUserName}}</p>
                          <template v-if="item.status==6 && Number(item.homeScore)==0">
                            <div class="giveup">已弃权</div>
                          </template>                          
                          <el-button type="link" 
                            v-if="!item.homeScore && item.status!==4 && item.status!==6"
                            @click="giveUp($event, item,'host')">弃权</el-button>
                      </div>
                    </div>
                  </el-col>
                  <el-col :span="2">
                     <e-img-match :src="item.hostIconUrl"/>
                  </el-col>
                  <el-col :span="3">
                    <div class="match-vs">
                      <p v-if="!item.homeScore && (!item.guestScore)" class="match-vers">vs</p>
                      <p v-if="item.end|| item.guestScore" class="match-vers">{{item.homeScore}}:{{item.guestScore}}</p>
                      <el-button type="link" v-if="!item.homeScore && item.status!==4 && item.status!==6" 
                        @click="openScore($event, item)">录入比分</el-button>
                    </div>
                  </el-col>
                  <el-col :span="2">
                      <e-img-match :src="item.guestIconUrl" />
                  </el-col>
                  <el-col :span="4">
                    <div class="team">
                      <div class="tm-name">
                          <p v-if="doubleType.includes(race_detail.joinRequire)">{{item.guestUserName}} & {{item.guestUserName2}}</p>
                          <p v-else>{{item.guestUserName}}</p>
                          <template v-if="item.status==6 && item.guestScore==0">
                            <div class="giveup">已弃权</div>
                          </template> 
                          <el-button v-if="!item.homeScore && item.status!==4 && item.status!==6"
                            type="link"  @click="giveUp($event, item,'guest')">弃权</el-button>
                      </div>
                    </div>
                  </el-col>
                  <el-col :span="5">
                    <!--status: 0、初始化（2轮以上赛事默认使用），1、待比赛，2、已结束，3、延迟比赛，4、取消比赛，5轮空-->
                    <div v-if="item.status!==4 &&  item.status!==6 && item.status !=2">
                      <el-button v-show="!item.homeScore" class="tiny" size="mini" @click="editGame(item)">编辑比赛</el-button>
                      <el-button v-show="!item.homeScore" class="tiny" size="mini" @click="showCancel(item)">取消比赛</el-button>                                          
                    </div>
                    <div v-if="item.status==4">
                      <span  class="canceled">已取消</span>
                    </div>
                    <div v-if="item.status==6">
                      <span class="canceled" v-if="item.homeScore==0">主队弃权</span>
                      <span class="canceled" v-if="item.guestScore==0">客队弃权</span>
                    </div>
                    <div v-if="item.status==2 && isGroup">
                      <el-button size="small" @click="lookDetails(item)">
                        查看比分详情
                      </el-button>
                    </div>
                    <div v-if="item.status==2 && hasScoreDetail">
                      <el-button size="small" @click="getScoreDetail(item)">
                        查看比分详情
                      </el-button>
                    </div>
                  </el-col>
                </el-row>                
            </li>
           </ul>

           <div class="button-box">
             <el-button type="primary" @click="exportExcel()">导出Excel</el-button>
           </div>
        </div>

        <div class="no-match" v-else>没有比赛</div>
        
        
        <!-- 取消比赛弹框 --> 
        <cancel-game-dialog
          v-if="cancelVisible"
          :visible.sync="cancelVisible"
          @close="hideMessageBox"
          @cancel="hideMessageBox"
          @confirm="cancelGame">
        </cancel-game-dialog>

        <!--大比分弹框-->
        <el-dialog 
          class="score-dialog"
          :visible.sync="scoreVisible"
          :title="'请输入最终比分'"
          @close="closeScore()">
          <div class="relative">
            <div style="margin-bottom:10px;">
              <label class="game-name hidden" v-if="doubleType.includes(race_detail.joinRequire)">{{game.hostUserName}} & {{game.hostUserName2}}</label>
              <label class="game-name hidden" v-else>{{game.hostUserName}}</label>
              <el-input class="score-input" v-model.trim="homeScore" :maxlength="3">
                <template slot="append">分</template>
              </el-input>
            </div>
            <div>
              <label class="game-name hidden" v-if="doubleType.includes(race_detail.joinRequire)">{{game.guestUserName}} & {{game.guestUserName2}}</label>
              <label class="game-name hidden" v-else>{{game.guestUserName}}</label>
              <el-input class="score-input" v-model.trim="guestScore" :maxlength="3">
                <template slot="append">分</template>
              </el-input>
            </div>
            <el-popover   
              class="pop-over" ref="popover5"
              placement="top"  width="200"
              v-model="popVisible">
              <p class="warnning">比分一经录入不能再次修改，是否确认录入？</p>
              <div style="text-align: right; margin: 0">
                <el-button size="mini" type="text" @click="popVisible = false">取消</el-button>
                <el-button size="mini" type="primary" @click="scoreWrite()">确定</el-button>
              </div>        
            </el-popover>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="closeScore()">取 消</el-button>
            <el-button type="primary" @click="checkPoint()">确 定</el-button>
          </span>        
        </el-dialog>

        <!--团体赛小比分弹框-->
        <score-group
          v-if="scoreGroupVisible"
          :visible="scoreGroupVisible"
          :data="match"
          :detail="scoreGroup"
          :isRead="isRead"
          @close="scoreGroupVisible=false"
          @score="handleScore">
        </score-group>

        <!--小比分弹框--> 
        <score-dialog
          v-if="scoreDetailsVisible"
          :isRead="isReadScore"
          :visible="scoreDetailsVisible"
          :data="scoreDetail"
          :result="scoreResult"
          :host="game.hostUserName + (game.hostUserName2 ? '&'+game.hostUserName2 : '')"
          :guest="game.guestUserName + (game.guestUserName2 ? '&'+game.guestUserName2 : '')"
          @score="score"
          @close="scoreDetailsVisible=false">
        </score-dialog>
    </div>
</template>

<script>
  import Api from 'api/race'
  import {downloadFile, matchFormat, groupRaceFormat, seqList, IsScoreDetail} from 'utils' // eslint-disable-line
  import DateSlider from './components/DateSlider'
  import PlaceGroup from './components/PlaceGroup'
  import CancelGameDialog from './components/CancelGameDialog.vue'
  import ScoreDialog from './components/ScoreDialog'
  import ScoreGroup from './components/ScoreGroup'
  import {mapGetters} from 'vuex'
  export default {
    components: {
      DateSlider,
      PlaceGroup,
      ScoreDialog,
      CancelGameDialog,
      ScoreGroup
    },
    computed: {
      ...mapGetters({
        race_detail: 'race_detail'
      }),
      isGroup () { // 网羽乒团体赛
        return [300501, 300401, 300301].indexOf(this.race_detail.matchType) > -1
      },
      hasScoreDetail () {
        return IsScoreDetail(this.race_detail)
      }
    },
    mounted () {
      this.getPreview()
    },
    data () {
      return {
        popVisible: false,
        scoreDetailsVisible: false, // 小比分弹框
        scoreResult: {},
        scoreDetail: {},
        dateList: [],
        activeDate: {},
        selectedIndex: 0,
        dateIndex: 0,
        matchList: [],
        gameList: [],
        homeScore: '',
        guestScore: '',
        cancelCase: 0, // 取消原因
        cancelVisible: false, // 取消比赛弹框
        scoreVisible: false, // 录入比分弹框
        canceledGame: {},
        game: {}, // 录入比分的比赛
        doubleType: [20006, 20008, 20010], // 双人类型赛事
        isRead: false,
        scoreGroup: {},
        scoreGroupVisible: false,
        match: {}
      }
    },
    methods: {
      checkPoint () {
        if ((Number.isInteger(parseInt(this.homeScore))) && (Number.isInteger(parseInt(this.guestScore))) &&
          parseInt(this.homeScore) >= 0 && parseInt(this.guestScore) >= 0) {
          this.popVisible = true
        } else {
          this.$message({
            type: 'error',
            message: '比分请输入非负整数'
          })
          return false
        }
      },
      hideMessageBox () {
        this.cancelVisible = false
      },
      // 获取赛程预览导航栏
      getPreview () {
        Api.getSchedulePreview({matchId: this.$route.query.id}, this).then((data) => {
          this.dateList = data.data || []
          if (this.dateList.length) {
            this.activeDate = this.dateList[0]
            this.getScheduleInfo(this.activeDate)
            this.selectedIndex = 0
          }
        })
      },
      // 获取某一天的赛程信息
      getScheduleInfo (date) {
        Api.getScheduleInfo({
          matchId: this.$route.query.id,
          day: typeof date === 'string' ? date : date.scheduleDate
        }, this).then((data) => {
          this.matchList = data.data
          this.gameList = this.matchList[this.selectedIndex].matchScheduleResp
        })
      },
      handleCheck (obj) {
        if (obj.matchNumber > 0) {
          this.getScheduleInfo(obj)
          this.selectedIndex = 0
        } else {
          this.gameList = []
          this.matchList = []
        }
      },
      handleSelect (index) {
        this.selectedIndex = index
        this.gameList = this.matchList[index].matchScheduleResp
      },
      // 比赛弃权
      giveUp (event, item, team) {
        let isHost = team === 'host' ? 1 : 0
        let text = ''
        if (isHost) {
          text = '主队：' + item.hostUserName + (item.hostUserName2 ? '&' + item.hostUserName2 : '')
        } else {
          text = '客队：' + item.guestUserName + (item.guestUserName2 ? '&' + item.guestUserName2 : '')
        }
        this.$confirm(`确认${text}弃权？`, '提示', {
          type: 'warning'
        }).then(() => {
          Api.matchGiveup({
            id: item.id,
            hostUserId: item.hostUserId,
            guestUserId: item.guestUserId,
            status: 6, // 4：取消比赛，5：轮空，6：弃权
            result: isHost ? 3 : 4 // 3：主队弃权，4：客队弃权
          }, {context: event.target}).then((res) => {
            item.end = 1
            item.status = 6
            item.homeScore = res.data.hostScore
            item.guestScore = res.data.guestScore
          }).catch((err) => {
            this.$message({
              type: 'warning',
              message: err.msg
            })
          })
        }).catch(() => {
        })
      },
      // open比分录入弹框
      openScore (event, item) {
        if (this.isGroup) {
          if (!item.sequence) {
            Api.getSequence({
              matchId: this.$route.query.id,
              matchScheduleId: item.id
            }).then((res) => {
              item.sequence = seqList(res.data)
              this.match = Object.assign({}, {id: item.id, sequence: item.sequence, hostTeam: item.hostUserName, guestTeam: item.guestUserName}, groupRaceFormat(this.race_detail))
              this.scoreGroupVisible = true
            })
          } else {
            this.match = Object.assign({}, {id: item.id, sequence: item.sequence, hostTeam: item.hostUserName, guestTeam: item.guestUserName}, groupRaceFormat(this.race_detail))
            this.scoreGroupVisible = true
          }
          this.isRead = false
        } else {
          if (this.hasScoreDetail) {
            this.isReadScore = false
            this.scoreDetail = matchFormat(this.race_detail)
            this.scoreDetailsVisible = true
          } else {
            this.scoreVisible = true
          }
        }
        this.game = item
      },
      // 关闭弹框并重置 主队客队比分
      closeScore () {
        this.scoreVisible = false
        this.homeScore = ''
        this.guestScore = ''
        this.popVisible = false
      },
      // 比分录入
      scoreWrite () {
        if ((Number.isInteger(parseInt(this.homeScore))) && (Number.isInteger(parseInt(this.guestScore))) &&
          parseInt(this.homeScore) >= 0 && parseInt(this.guestScore) >= 0) {
          Api.scoreWrite({
            id: this.game.id,
            hostScores: this.homeScore,
            guestScores: this.guestScore
          }, {context: event.target}).then((res) => {
            this.game.homeScore = this.homeScore
            this.game.guestScore = this.guestScore
            this.closeScore()
          }).catch((err) => {
            this.popVisible = false
            console.log(err.msg)
          })
        } else {
          this.$message({
            type: 'error',
            message: '比分请输入非负整数'
          })
          return false
        }
      },
      showCancel (item) {
        this.canceledGame = item
        this.cancelVisible = true
      },
      // 取消比赛
      cancelGame (obj) {
        Api.matchCancel({
          id: this.canceledGame.id,
          cancleCase: obj.cancelCase,
          remark: obj.remark
        }, {context: this}).then((res) => {
          this.canceledGame.status = 4
          this.$message({
            type: 'success',
            message: '取消成功!'
          })
          this.hideMessageBox()
          this.activeDate.matchNumber--
        }).catch((err) => {
          this.$message({
            type: 'warning',
            message: err.msg
          })
          this.hideMessageBox()
        })
      },
      // 编辑比赛
      editGame (item) {
        this.$store.commit('MATCH_DETAIL', item)
        this.$router.push({
          path: '/race/detail/manage/matchedit',
          query: {
            id: this.$route.query.id,
            gameId: item.id,
            isRun: this.$route.query.isRun,
            tasktype: this.$route.query.tasktype
          }
        })
      },
      exportExcel () {
        var url = '/api/match/schedule/export/schedulePrevInfo?matchId=' + this.$route.query.id
        var _this = this
        downloadFile(url, '赛程预览.xls', function (blob) {
          _this.$message({
            message: '下载出错，请稍后再试',
            type: 'warning'
          })
        })
      },
      // 录入团体比分
      handleScore (data) {
        Api.score(data).then((res) => {
          this.scoreGroupVisible = false
          this.getScheduleInfo(this.activeDate)
        })
      },
      // 查看团体小比分
      lookDetails (item) {
        this.isRead = true
        if (item.scoreList) {
          this.scoreGroup = item.scoreList
          this.scoreGroupVisible = true
        } else {
          Api.getGroupScore({
            matchScheduleId: item.id
          }).then((res) => {
            let sg = {
              hostTeam: item.hostUserName,
              guestTeam: item.guestUserName,
              hostScore: res.data.hostScore,
              guestScore: res.data.guestScore,
              scoreList: res.data.mssvo
            }
            item.scoreList = Object.assign({}, groupRaceFormat(this.race_detail), sg)
            this.scoreGroup = item.scoreList
            this.scoreGroupVisible = true
          })
        }
      },
      // 录入小比分
      score (val) {
        Api.scoreDetail({
          id: this.game.id,
          hostScore: val.hostScore,
          guestScore: val.guestScore,
          hostUserId: this.game.hostUserId,
          guestUserId: this.game.guestUserId,
          roundType: String(this.race_detail.formatNumberType),
          scoreGameVO: val.scoreGameVO
        }, {context: event.target}).then((res) => {
          this.game.homeScore = this.homeScore
          this.game.guestScore = this.guestScore
          let theday = new Date(this.game.startTime).format('yyyy-MM-dd')
          this.getScheduleInfo(theday)
          for (var i = 0, l = this.dateList.length; i < l; i++) {
            if (this.dateList[i].scheduleDate === theday) {
              this.activeDate = this.dateList[i]
            }
          }
          this.scoreDetailsVisible = false
        }).catch((err) => {
          console.log(err.msg)
        })
      },
      // 查看个人赛小比分
      getScoreDetail (item) {
        this.isReadScore = true
        if (item.scoreList) {
          this.scoreResult = item.scoreList
          this.scoreDetailsVisible = true
        } else {
          Api.getScoreDetail({
            matchScheduleId: item.id
          }).then((res) => {
            let game = matchFormat(this.race_detail)
            item.scoreList = {
              roundType: game.roundType,
              scoreList: res.data.smallScoreScanVO || [],
              hostUserName: item.hostUserName + (item.hostUserName2 ? '&' + item.hostUserName2 : ''),
              guestUserName: item.guestUserName + (item.guestUserName2 ? '&' + item.guestUserName2 : ''),
              hostScore: res.data.hostScore,
              guestScore: res.data.guestScore,
              dish: game.dish
            }
            this.scoreResult = item.scoreList
            this.scoreDetailsVisible = true
          })
        }
      }
    }
  }
</script>

<style scoped rel="stylesheet/scss" lang="scss">
 
@import '../../styles/scheduleEdit.scss';
</style>
<style lang="scss">
.pop-over{
  .el-popover{
    right: 20px;
    top: 68px;
    display: block;
  }
  .warnning{
    line-height: 20px;
    margin-bottom: 5px;
    font-size: 14px;
  }
}
.score-dialog{
  .el-dialog{
    width: 420px;
    .el-dialog__body{
      text-align:center;
    }
  }
}
.score-input{
  display: inline-block;
}
</style>
